package com.ruoyi.video.init;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.video.common.MediaConstant;
import com.ruoyi.video.domain.Device;
import com.ruoyi.video.domain.dto.CameraDto;
import com.ruoyi.video.mapper.DeviceMapper;
import com.ruoyi.video.server.MediaServer;
import com.ruoyi.video.service.HlsService;
import com.ruoyi.video.service.MediaService;
import jakarta.annotation.PostConstruct;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.Iterator;
import java.util.List;

import org.bytedeco.ffmpeg.ffmpeg;
import org.bytedeco.javacpp.Loader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

/**
 * @Author: orange
 * @CreateTime: 2025-01-16
 */
@Component
public class InitServer implements CommandLineRunner {
    // 定义日志对象
    private static final Logger log = LoggerFactory.getLogger(InitServer.class);
    // 注入mediasServer.port的值
    @Value("${mediasServer.port}")
    private int port;
    // 注入MediaServer对象
    @Autowired
    private MediaServer mediaServer;
    // 注入MediaService对象
    @Autowired
    private MediaService mediaService;
    // 注入HlsService对象
    @Autowired
    private HlsService hlsService;
    // 注入DeviceMapper对象
    @Autowired
    private DeviceMapper deviceMapper;
    // 注入Environment对象
    @Autowired
    private Environment env;

    public InitServer() {
    }

    // 实现CommandLineRunner接口的run方法
    public void run(String... args) throws Exception {
        // 初始化自动播放
        this.initAutoPlay();
        // 获取本机IP地址
        String ip = InetAddress.getLocalHost().getHostAddress();
        // 获取http端口号
        String httpPort = this.env.getProperty("server.port");
        // 获取web路径
        String path = this.env.getProperty("server.servlet.context-path");
        if (StrUtil.isEmpty(path)) {
            path = "";
        }

        // 打印启动信息
        log.info("\n--------------------------------------------------------- \n" +
                        "\t RTSP视频分析平台启动成功! Access address: \n" +
                        "\t media port at : \t {} \n" +
                        "\t http port at : \t {} \n" +
                        "\t web Local: \t http://localhost:{} \n" +
                        "\t web External: \t http://{}:{}{} \n" +
                        "\t httpflv: \t http://{}:{}/live?url={您的源地址} \n" +
                        "\t wsflv: \t ws://{}:{}/live?url={您的源地址} \n" +
                        "\t hls(m3u8): \t http://{}:{}/hls?url={您的源地址} \n" +
                        "\t h2-database: \t http://{}:{}/h2-console \n" +
                        "\t 作者微信: \t chenbai0511 \n" +
                        "\t 请我喝杯咖啡吧qwq \n" +
                        "--------------------------------------------------------- \n",
                port,
                httpPort,
                httpPort,
                ip, httpPort, path,
                ip, port,
                ip, port,
                ip, httpPort,
                ip, httpPort);
        // 启动MediaServer
        this.mediaServer.start(new InetSocketAddress("0.0.0.0", this.port));
    }

    // 初始化自动播放
    public void initAutoPlay() {
        // 获取设备列表
        List<Device> devices = this.deviceMapper.selectDeviceList(new Device());
        if (null != devices && !devices.isEmpty()) {
            log.info("已启动自动拉流！");
            Iterator var2 = devices.iterator();

            while (var2.hasNext()) {
                Device device = (Device) var2.next();
                CameraDto cameraDto = new CameraDto();
                cameraDto.setUrl(device.getUrl());
                cameraDto.setAutoClose(false);
                cameraDto.setEnabledFFmpeg(device.getEnabledFlv().equals("0"));
                cameraDto.setEnabledFlv(device.getEnabledFlv().equals("0"));
                cameraDto.setEnabledHls(device.getEnabledHls().equals("0"));
                cameraDto.setMediaKey(device.getMediaKey());
                if (device.getEnabledFlv().equals("0")) {
                    this.mediaService.playForApi(cameraDto);
                }

                if (device.getEnabledHls().equals("0")) {
                    this.hlsService.startConvertToHls(cameraDto);
                }
            }
        }

    }

    // 在初始化后加载FFmpeg
    @PostConstruct
    public void loadFFmpeg() {
        String ffmpeg = Loader.load(org.bytedeco.ffmpeg.ffmpeg.class);
        System.setProperty(MediaConstant.ffmpegPathKey, ffmpeg);
        log.info("初始化资源成功");
    }
}
